<?php
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Lib/Base.php';
require_once __DIR__ . '/funcs.php';
require_once __DIR__ . '/Lib/Page.php';

checkLogin();

// 权限检查
$funcs = getFuncs($_SESSION['admin_group']);
checkFunc(13);

global $plat_db;

$error = $success = NULL;
$now = time();
$today = date('Y-m-d');

$default_search_start_day = date('Y-m-01');
$start_time = $_GET['start'] ?? null;
$end_time   = $_GET['end']   ?? null;
if(!$start_time) $start_time = null;
if(!$end_time) $end_time = null;
if($start_time !== null) $start_time = strtotime($start_time.' 00:00:00');
if($end_time !== null) $end_time   = strtotime($end_time.' 23:59:59');
if($start_time === null) $start_time = strtotime($default_search_start_day.' 00:00:00');
if($end_time === null) $end_time = strtotime($today.'23:59:59');
$search_start_day = date('Y-m-d', $start_time);
$search_end_day   = date('Y-m-d', $end_time);

$account = $_GET['account'] ?? null;
$logaction = $_GET['logaction'] ?? null;
$search_module = $search_action = null;
if($logaction) {
    $logarr = explode(':', $logaction);
    $search_module = $logarr[0];
    $search_action = $logarr[1];
}
$page = $_GET['page'] ?? 1;

$where = [
    'time[>=]'=>$start_time,
    'time[<=]'=>$end_time,
];
if($account) $where["user"] = $account;
if($logaction) {
    $where["module"] = $search_module;
    $where['action'] = $search_action;
}

// 获取总数
$total = $DB->count('admin_operation_log', $where);
$pagesize = 15;
$total_page = ceil($total / $pagesize);
if($page > $total_page) $page = $total_page;
if($page < 1) $page = 1;
$offset = ($page - 1) * $pagesize;

// 获取记录内容
$where['ORDER'] = ['id'=>'DESC'];
$where['LIMIT'] = [$offset, $pagesize];
$log_list = $DB->select('admin_operation_log', '*', $where);

$op_user = [];
$find_user = $DB->select('admin_user', ['id','username']);
foreach($find_user as $fu) {
    $op_user[$fu['id']] = $fu['username'];
}

display_header();

?>

<section class="content">

	<?php display_title('操作日志'); ?>

	<div class="box box-warning">
		<div class="box-header with-border">
			<h3 class="box-title"><i class="fa fa-search"></i> 结果筛选</h3>
			<?php if($start_time || $logaction) { ?>
                <div style="display:inline-block;margin-left:30px;" class="filter_box">
                    当前筛选条件
                    <?php
                        if($start_time && $end_time) {
                        echo '<div>时间段:　<strong>' . date('Y-m-d', $start_time) . ' ~ ' . date('Y-m-d', $end_time) . '</strong>';
                            echo '<span class="badge bg-red" onclick="filter_go(\'time\');">X</span></div>';
                        }
                        if($logaction) {
                        echo '<div>操作类型: <strong>' . LOG_MODULE[$search_module]['name'] . ' - ' . LOG_MODULE[$search_module]['action'][$search_action] . '</strong><span class="badge bg-red" onclick="filter_go(\'logaction\');">X</span></div>';
                        }
                    ?>
                </div>
			<?php } ?>
		</div>

		<div class="box-body">
			<div class="line">
				<form action="log.php" method="get">
					<button type="button" class="btn btn-default pull-left" id="daterange-btn">
						<span>请选择时间段</span>
						<i class="fa fa-caret-down"></i>
					</button>
                    <div class="pull-left" style="padding:0px 15px; display:inline-block;">
                        开始时间: <input type="text" style="width:100px;display:inline-block;" id="search_start_date" name="start"
                                     class="form-control" readonly value="<?php echo $search_start_day; ?>" />
                    </div>
                    <div class="pull-left" style="padding:0px 15px 0px 0px; display:inline-block;">
                        结束时间: <input type="text" style="width:100px;display:inline-block;" name="end" id="search_end_date" class="form-control"
                                     value="<?php echo $search_end_day; ?>" readonly />
                    </div>
                    <div class="pull-left" style="padding:0px 15px; display:inline-block;line-height:32px;">
                        <div class="pull-left">执行账号:&nbsp;&nbsp;</div>
                        <select class="form-control" name="account" style="display:inline !important;float:left;width:auto;">
                            <option value=""></option>
                            <?php foreach($op_user as $ui => $un) { ?><option <?php if($account==$ui) echo ' selected '; ?> value="<?php echo $ui; ?>"><?php echo $un; ?></option><?php } ?>
                        </select>
                    </div>
                    <div class="pull-left" style="padding:0px 15px; display:inline-block;line-height:32px;">
                        <div class="pull-left">操作类型:&nbsp;&nbsp;</div>
                        <select class="form-control" name="logaction" style="display:inline !important;float:left;width:auto;">
                            <option value=""></option>
							<?php
                                foreach(LOG_MODULE as $_module => $_minfo) {
                                    $mname = $_minfo['name'];
                                    echo '<optgroup label="'.$mname.'">';
                                    foreach($_minfo['action'] as $_akey => $_action) {
                            ?>
                                <option <?php if($search_module == $_module && $search_action == $_akey) echo ' selected '; ?> value="<?php echo $_module.':'.$_akey; ?>"><?php echo $_action; ?></option>
                            <?php
                                    }
                                    echo '</optgroup>';
                                }
                            ?>
                        </select>
                    </div>
					<button type="submit" class="btn btn-primary pull-left">查看数据</button>
				</form>
			</div>
		</div>
	</div>

	<div class="box box-primary">
		<div class="box-header with-border">
			<h3 class="box-title"><i class="fa fa-search"></i> 操作日志</h3>
		</div>

		<div class="box-body">

            <table id="logtable" class="table table-bordered table-striped dataTable table-hover table-condensed" role="grid" aria-describedby="example1_info">
                <thead>
                <tr>
                    <th class="" rowspan="1" colspan="1" width="50" style="text-align:center">ID</th>
                    <th class="" rowspan="1" colspan="1" width="150" style="text-align:center;">模块</th>
                    <th class="" rowspan="1" colspan="1" width="150" style="text-align:center;">动作</th>
                    <th class="" rowspan="1" colspan="1">操作详情</th>
                    <th class="" rowspan="1" colspan="1" width="100" style="text-align:center">执行账号</th>
                    <th class="" rowspan="1" colspan="1" width="180" style="text-align:center">时间</th>
                    <th class="" rowspan="1" colspan="1" width="100" style="text-align:center">IP地址</th>
                </tr>
                </thead>
                <tbody>
				<?php if(!empty($log_list)) { foreach($log_list as $log) { ?>
                <tr role="row" style="text-align:center;">
                    <td><?php echo $log['id']; ?></td>
                    <td><?php echo LOG_MODULE[$log['module']]['name'] ?? $log['module']; ?></td>
                    <td><?php echo LOG_MODULE[$log['module']]['action'][$log['action']] ?? $log['action']; ?></td>
                    <td style="font-size:10px;text-align:left;">
                        <div style="word-wrap:break-word;word-break:break-all;">
                        <?php
                            if($log['params']=='[]') echo '-';
                            else {
                                $arr = json_decode($log['params'], true);
                                foreach($arr as $k => $v) {
                                    echo '<strong>'.$k.'</strong>' . " : ";
                                    echo is_array($v) ? json_encode($v) : $v;
                                    echo "<br />";
                                }
                            }
                        ?>
                        </div>
                    </td>
                    <td><?php echo @$op_user[$log['user']]; ?></td>
                    <td style="font-size:12px;"><?php echo date('Y-m-d H:i:s', $log['time']); ?></td>
                    <td style="font-size:10px;vertical-align:middle;">
                        <a style="cursor:pointer;" data-toggle="modal" data-target="#modal-findip" ip="<?php echo long2ip($log['ip']); ?>"><?php echo long2ip($log['ip']); ?></a>
                    </td>
                </tr>
                <?php } } ?>
                </tbody>
            </table>

            <?php pagination('log.php', $_GET, $page, $total, $pagesize); ?>

	<?php if($error) : ?>
		<div class="alert alert-warning alert-dismissible">
			<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
			<?php echo $error; ?>
		</div>
	<?php endif ?>

</section>

<!-- 查询IP -->
<div class="modal fade" id="modal-findip"><div class="modal-dialog" style="width:300px;"><div class="modal-content">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">IP归属地<br /><span style="font-size:12px;color:#999;">两次查询IP的间隔不要太短<br />第三方接口,请求过多会被屏蔽<br />内网IP或获取不到的都会显示广州市</span></h4></div>
    <div class="modal-body">
        <div id="iamip"></div>
    </div>
</div></div></div>

<!-- jQuery 3 -->
<script src="js/jquery.min.js"></script>
<script src="js/jquery.cookie.js"></script>
<script src="js/pace.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Select2 -->
<script src="bower_components/select2/dist/js/select2.full.min.js"></script>
<!-- InputMask -->
<script src="plugins/input-mask/jquery.inputmask.js"></script>
<script src="plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
<script src="plugins/input-mask/jquery.inputmask.extensions.js"></script>
<!-- date-range-picker -->
<script src="bower_components/moment/min/moment.min.js"></script>
<script src="bower_components/bootstrap-daterangepicker/daterangepicker.js"></script>
<!-- bootstrap datepicker -->
<script src="bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js"></script>
<!-- bootstrap time picker -->
<script src="plugins/timepicker/bootstrap-timepicker.min.js"></script>
<!-- SlimScroll -->
<script src="bower_components/jquery-slimscroll/jquery.slimscroll.min.js"></script>
<!-- iCheck 1.0.1 -->
<script src="plugins/iCheck/icheck.min.js"></script>
<!-- FastClick -->
<script src="bower_components/fastclick/lib/fastclick.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/adminlte.min.js"></script>
<script type="text/javascript">
    function filter_go(filter) {
        var href = window.location.href;
        var href_arr = href.split('?');
        if(!href_arr[1]) {
            return false;
        }
        var args_list = href_arr[1].split('&');
        var new_args = [];
        for(k in args_list) {
            var arg_arr = args_list[k].split('=');
            if(filter == 'time' && (arg_arr[0] == 'start' || arg_arr[0] == 'end')) continue;
            else if(filter == 'logaction' && arg_arr[0] == 'logaction') continue;
            else if(arg_arr[1] == '') continue;
            else if(arg_arr[0] == 'page') continue;
            else new_args.push(args_list[k]);
        }
        var new_arg_str = new_args.join('&');
        if(new_arg_str.length > 0) var new_url = href_arr[0] + '?' + new_arg_str;
        else var new_url = href_arr[0];
        location.href = new_url;
    }

    $(function() {
        var locale = {
            "format": 'YYYY-MM-DD',
            "separator": " -222 ",
            "applyLabel": "确定",
            "cancelLabel": "取消",
            "fromLabel": "起始时间",
            "toLabel": "结束时间'",
            "customRangeLabel": "自定义",
            "weekLabel": "W",
            "daysOfWeek": ["日", "一", "二", "三", "四", "五", "六"],
            "monthNames": ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
            "firstDay": 1
        };

        $('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
            checkboxClass: 'icheckbox_minimal-blue',
            radioClass   : 'iradio_minimal-blue'
        })
        //Red color scheme for iCheck
        $('input[type="checkbox"].minimal-red, input[type="radio"].minimal-red').iCheck({
            checkboxClass: 'icheckbox_minimal-red',
            radioClass   : 'iradio_minimal-red'
        })
        $('input[type="checkbox"].flat-red, input[type="radio"].flat-red').iCheck({
            checkboxClass: 'icheckbox_flat-green',
            radioClass   : 'iradio_flat-green'
        });

        $('#daterange-btn').daterangepicker(
            {
                locale   : locale,
                ranges   : {
                    '今日'       : [moment(), moment()],
                    '昨日'   : [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                    '最近7日' : [moment().subtract(6, 'days'), moment()],
                    '本月'  : [moment().startOf('month'), moment().endOf('month')],
                    '上月'  : [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
                    '近3个月'  : [moment().subtract(2, 'month').startOf('month'), moment().endOf('month')],
                    '今年'  : [moment().startOf('year'), moment().endOf('year')]
                },
                startDate: '<?php echo $search_start_day; ?>',
                endDate  : '<?php echo $search_end_day; ?>'
            },
            function (start, end) {
                $('#search_start_date').val(start.format('YYYY-MM-DD'));
                $('#search_end_date').val(end.format('YYYY-MM-DD'));
            }
        );

        $('input[name="start"]').daterangepicker({
            locale: locale,
            singleDatePicker: true,
            showDropdowns: true,
            minYear: 1901,
            maxYear: parseInt(moment().format('YYYY'),10)
        }, function(start) {
            //$('#search_start_date').val(start.format('YYYY-MM-DD'));
        });

        $('input[name="end"]').daterangepicker({
            locale: locale,
            singleDatePicker: true,
            showDropdowns: true,
            minYear: 1901,
            maxYear: parseInt(moment().format('YYYY'),10)
        }, function(end) {
            //$('#search_end_date').val(end.format('YYYY-MM-DD'));
        });

        $('#modal-findip').on('show.bs.modal', function (e) {
            var modal = $(this);
            var btn = $(e.relatedTarget);
            var ip = btn.attr('ip');
            var res = '';
            $('#iamip').html('');
            $.ajax({
                url: 'player_action.php?action=getip&ip=' + ip,
                beforeSend: function() {
                },
                success: function(data) {
                    res = JSON.parse(data);
                    // $('#iamip').html('<strong>IP地址</strong>:<br />&nbsp;&nbsp;&nbsp;&nbsp;' + ip + '<br /><strong>归属信息</strong>: <br />'
                    //     + '&nbsp;&nbsp;&nbsp;&nbsp;国家:' + res.data.data.country + '<br />'
                    //     + '&nbsp;&nbsp;&nbsp;&nbsp;省份:' + res.data.data.region + '<br />'
                    //     + '&nbsp;&nbsp;&nbsp;&nbsp;城市:' + res.data.data.city + '<br />'
                    //     + '&nbsp;&nbsp;&nbsp;&nbsp;运营商:' + res.data.data.isp
                    // );
                    eval(res.data);
                    $('#iamip').html('<strong>IP地址</strong>:<br />&nbsp;&nbsp;&nbsp;&nbsp;' + ip + '<br /><strong>归属信息</strong>: <br />'
                        //+ '&nbsp;&nbsp;&nbsp;&nbsp;国家:' + res.data.data.country + '<br />'
                        + '&nbsp;&nbsp;&nbsp;&nbsp;省份:' + lo + '<br />'
                        + '&nbsp;&nbsp;&nbsp;&nbsp;城市:' + lc + '<br />'
                        //+ '&nbsp;&nbsp;&nbsp;&nbsp;运营商:' + res.data.data.isp
                    );
                }
            });
        });

        setTimeout(function() {
            $('.alert-success').fadeOut();
            if($('.alert-warning').find('span').html() && $('.alert-warning').find('span').html().length < 60) {
                $('.alert-warning').fadeOut();
            }
        }, 2000);
    });
</script>

</body>
</html>
